package br.com.rubrol.webservice;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBElement;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.rubrol.util.HibernateUtil;

@SuppressWarnings("unchecked")
public abstract class GenericWS<T> {
	private Session session = HibernateUtil.getSessionFactory().openSession();

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public String getVersion() {
		return "Release 0.9";
	}
	
	@GET
	@Path("{codigo}")
	@Consumes(MediaType.TEXT_PLAIN)
	@Produces(MediaType.APPLICATION_JSON)
	public T getObj(@PathParam("codigo") int codigo) {
		try {
			Query hql = getQuery(session, codigo);

			T obj = (T) hql.uniqueResult();
			return obj;
		} catch (Exception ex) {
			return null;
		}
	}

	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public T editMaquina(JAXBElement<T> obj) {
		try {
			Transaction tx = session.beginTransaction();
			T novo = obj.getValue();
			T result = (T) session.merge(novo);
			tx.commit();
			
			return result;
		} catch (HibernateException ex) {
			return null;
		}
	}
	
	@DELETE
	@Path("{codigo}")
	@Consumes(MediaType.TEXT_PLAIN)
	public Response remMaquina(@PathParam("codigo") int codigo) {
		try {
			Transaction tx = session.beginTransaction();
			
			Query hql = getQuery(session, codigo);

			T obj = (T) hql.uniqueResult();
		    
		    if(obj != null) {
		    	session.delete(obj);
		    	tx.commit();
				return Response.ok().build();
		    } else {
				return Response.status(400).build();
		    }
		} catch(HibernateException ex) {
			return Response.status(400).build();
		}
	}
	
	protected abstract Query getQuery(Session session, int codigo);
}
